package com.lds.sign_sdk.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Date 2022/1/7
 * @Time 15:33
 * @Author liudongs
 * @E-mail liudongs@aliyun.com
 * @Version 1.0.0
 * @Description
 **/
public class MD5Util {
    private static final String KEY_MAC = "HmacMD5";
    private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public MD5Util() {
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        byte[] var2 = b;
        int var3 = b.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            byte aB = var2[var4];
            resultSb.append(byteToHexString(aB));
        }

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (b < 0) {
            n = b + 256;
        }

        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;

        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname != null && !"".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            }
        } catch (Exception var4) {
        }

        return resultString;
    }

    public static String MD5Encode(String origin) {
        String resultString = null;

        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } catch (Exception var3) {
        }

        return resultString;
    }

    @Deprecated
    public static String getHmacMD5Signature(Map<String, String> requestParam, String key) {
        String data = formPublicParam(requestParam);
        byte[] inputData = data.getBytes();
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacMD5");

        try {
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return byteArrayToHexString(mac.doFinal(inputData));
        } catch (Exception var7) {
            return null;
        }
    }

    private static String formPublicParam(Map<String, String> requestParam) {
        Map<String, String> params = new TreeMap();
        params.putAll(requestParam);
        return (String)params.entrySet().stream().map((e) -> {
            return (String)e.getKey() + "=" + (String)e.getValue();
        }).collect(Collectors.joining("&"));
    }

    /**
     * 对map进行加密
     * @param requestParam
     * @return
     */
    public static String getHmacMD5Signature(Map<String, String> requestParam) {
        String data = formPublicParam(requestParam);
        return md5(data);
    }

    /**
     * MD5加密
     * @param value
     * @return
     */
    public static String md5(String value){
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
            md5.update((value).getBytes("UTF-8"));
        }catch (NoSuchAlgorithmException error){
            error.printStackTrace();
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        byte b[] = md5.digest();
        int i;
        StringBuffer buf = new StringBuffer("");
        for(int offset=0; offset<b.length; offset++){
            i = b[offset];
            if(i<0){
                i+=256;
            }
            if(i<16){
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }
        //result = buf.toString().toUpperCase();
        return buf.toString();
    }

    /**
     * 盐值生成
     * @return
     */
    public final static String saltUtils(){

        /**
         *  如果字符种类不够，可以自己再添加一些
         */
        String range = "0123456789abcdefghijklmnopqrstuvwxyz";
        ThreadLocalRandom random = ThreadLocalRandom.current();

        StringBuilder result = new StringBuilder();
        result.append(System.currentTimeMillis());

        /**
         * 要生成几位，就把这里的数字改成几 目前业务要求三位随机码
         */
        for (int i = 0; i < 8; i++) {
            result.append(range.charAt(random.nextInt(range.length())));
        }

        return result.toString();
    }
}
